package io.renren.modules.app.utils;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.renren.modules.app.entity.DecryptMessage;
import io.renren.modules.app.entity.EncryptInfo;
import io.renren.modules.app.entity.Message;
import io.renren.modules.app.entity.WecomMessage;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;

import javax.crypto.Cipher;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

public class WecomUtils {
    static {

        if (isWindows()) {
            String path = "C:\\Users\\1\\.jdks\\corretto-1.8.0_452\\bin\\";
            System.out.println("----path-----------"+path.concat("libcrypto-1_1-x64.dll"));
            //加载顺序不能变
            System.load(path.concat("libcrypto-1_1-x64.dll"));
            System.load(path.concat("libssl-1_1-x64.dll"));
            System.load(path.concat("libcurl-x64.dll"));
            System.load(path.concat("WeWorkFinanceSdk.dll"));
        } else {
            // linux 加载指定so文件在linux系统下的位置
            System.load("/usr/lib/libWeWorkFinanceSdk.so");
            System.loadLibrary("WeWorkFinanceSdk");
        }


    }
    public static boolean isWindows() {
        String osName = System.getProperties().getProperty("os.name");
        return osName.toUpperCase().indexOf("WINDOWS") != -1;
    }


    public static String decrypt(String encryptSecretKey, String privateKeystr) {
        try {
            PemReader pemReader = new PemReader(new StringReader(privateKeystr));
            PemObject pemobject = pemReader.readPemObject();
            byte[] content = pemobject.getContent();
            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(content);
            KeyFactory factory = KeyFactory.getInstance("RSA");
            PrivateKey privateKey = factory.generatePrivate(spec);
            //先进行Base64解码
            byte[] decodedKey = Base64.getDecoder().decode(encryptSecretKey);
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] decryptedBytes = cipher.doFinal(decodedKey);
            // 将解密后的字节转换为字符串
            return new String(decryptedBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            System.out.println("企微会话存档encryptsecretKey解密失敗 >>>>>>>>>>");
            return "";
        }
    }


    /**
     * 对应的公钥
     *
     * -----BEGIN PUBLIC KEY-----
     * MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwC1Zf9GPz65VkxKa7UyG
     * 1OgonWCp3cry1yPFHOG7qQK/w4mTHcP82tqfMxwdse/btg60ks2n0ilCzWszzj/7
     * iRhAGdIfmTG5sMU2+Wjhv6ZPjQtDH6lkuNThU3Xq4W2HneVwstPM5JjedbQuYpQr
     * nhnegy9gDGG7KuGIZz/BrmDvCGUdE53uwoDGJo08VIAAX04imUKJ3UPQ558j71F6
     * CEekAeYvUoWbCWfS9z9KNwcHTMC+RxfWGgIvaSYOxWNsFTsZztTPrbFrOLeM48fJ
     * xu7HD9PdkWJz1LDZDUD516f6kZP/UJG0U8a8heQ0H3+S0/XGI6XGggCdhcQ6nH1y
     * TwIDAQAB
     * -----END PUBLIC KEY-----
     */

    public static String getDecryptMessage(List<WecomMessage> wecomMessageList) {
        String prikey =
                "-----BEGIN PRIVATE KEY-----\n" +
                        "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDALVl/0Y/PrlWT\n" +
                        "EprtTIbU6CidYKndyvLXI8Uc4bupAr/DiZMdw/za2p8zHB2x79u2DrSSzafSKULN\n" +
                        "azPOP/uJGEAZ0h+ZMbmwxTb5aOG/pk+NC0MfqWS41OFTderhbYed5XCy08zkmN51\n" +
                        "tC5ilCueGd6DL2AMYbsq4YhnP8GuYO8IZR0Tne7CgMYmjTxUgABfTiKZQondQ9Dn\n" +
                        "nyPvUXoIR6QB5i9ShZsJZ9L3P0o3BwdMwL5HF9YaAi9pJg7FY2wVOxnO1M+tsWs4\n" +
                        "t4zjx8nG7scP092RYnPUsNkNQPnXp/qRk/9QkbRTxryF5DQff5LT9cYjpcaCAJ2F\n" +
                        "xDqcfXJPAgMBAAECggEABCsXpV+YxHLuFT4SkTIXPJf6hYtas95ajRMQC/PTe7N9\n" +
                        "EFM0FzGwktiqGlQySrE+rUC9Zu/CA5t0gPshyQf3Pz6A6W520/5RnkVwz1EYkG0d\n" +
                        "jZwgbRfiAOZRKtvEZ/ZVujWHT8GrUIwGSzxIw0eeeJPsESFebnZSNnhk2oR2AX+8\n" +
                        "HqFQq+jKI7GXx73VpAAizNvQDPVHVOmg3E2+q/Q8loIRR4nWuiLfKhw2LcjUCID4\n" +
                        "t0D/ie/ZBHWEzyzJERezSYtyu/8gcAH4HzwbthsDqTxtXapuOOL8oAb8FKNJWoVR\n" +
                        "ij3e69z3ssNpaZ8txwDfeUeQBszqoggumBPsXcLR1QKBgQDmIuWYubYO/B0NYMFN\n" +
                        "gIog7vW6mpmBqhMmLmBkvoI9rQDX1PXCct+KiKvPa7BG5/8NKUWr+JHWxgQPEHVE\n" +
                        "ZkUcuU5SsO+9DxBmdT1ayx8esqTUXgjViD9VAwijvZjxsZSzGVoeS0PCxY7miOqf\n" +
                        "y8izOUVSsrEnzQalDNILoPtWywKBgQDVxlqiS8aMZUdFokxE8P7Svk36LiUnJCjf\n" +
                        "rsfkEtc+BfmqqNIfQjsgQ52dy09LGvvfFZM9uHAI0VRuj7EEYgqzoDoqt6C9aYTP\n" +
                        "mZCJZvU/yipS2LrA16oYyIrsiDqguIx4Q3mxKhApQJQw7aaTTb6IDWal+0ap4cMz\n" +
                        "ObsV6qLeDQKBgDzXUPe1cSo5AL0+rRv+NYZLZm9028xp2DIp5JX9v5TqneRxip9j\n" +
                        "mzGWvEVT5QB56PXjyWWTi4rKQtxwr2/r0a2sV8aIvHiw+Nb9e8D7HjkRZX43dgJt\n" +
                        "yMCC0s/nGf4bwoIu26JSp5FghUzxOYYRa/fl1ivszeUF0RHld8pXPttNAoGAC+mV\n" +
                        "u12FnuU154d3wI+9Y3j/V2Wi5F97d5uBwA/ctrQWiZAGxX8nVFDwQ47EyGakinXl\n" +
                        "UpcohxVDIzYWoyvjdMcE9sRszKFIqVjhWQbHu9pEKYGyRnS+IctrEms0+SfPjBQW\n" +
                        "f+zcIbBbka5sjeDTMTmt8qnh8i2GdyBMcJg2ozECgYAL7PzB8aCRj6FgTcrjfaDy\n" +
                        "k8aPudi2z1BaaEcSVT0876gBqV/xflDB34QnO4kpYPhMD6YP4h1YqzPYrvKqck0e\n" +
                        "5ese3snDh/lAjCEvnE791BsPQvOZH3FkVrq1XjhVsexcoGF70GYahh7469pqz95j\n" +
                        "p8vnuQB+QqMxkBWchQop1Q==\n" +
                        "-----END PRIVATE KEY-----";

//        Object o = JSONObject.parse(encryptMessage);
//        List<WecomMessage> wecomMessageList = ((JSONArray) o).toJavaList(WecomMessage.class);
        List<DecryptMessage> decryptMessageList = new ArrayList<>();
        wecomMessageList.forEach(m -> {
            EncryptInfo encryptInfo = new EncryptInfo();
            encryptInfo.setSecret_key(decrypt(m.getEncrypted_secret_key(), prikey));
            DecryptMessage decryptMessage = new DecryptMessage();
            decryptMessage.setMsgid(m.getMsg_id());
            decryptMessage.setEncrypt_info(encryptInfo);
            decryptMessageList.add(decryptMessage);
        });

        Message message = new Message();
        message.setKb_id("kbdH1Uz-6zT-zLpdUhYV_IFexIs-7CYTyU");
        message.setMsg_list(decryptMessageList);
        System.out.println(StrUtil.format("message = {}", JSONObject.toJSONString(message)));
        return JSONObject.toJSONString(message);
    }
}